package com.bingo.bounce.sdk.bridge;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;

import com.bingo.bounce.sdk.BBounceBusiness;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BBounceCocosBridge implements BBounceCocosIAP {

    private static BBounceCocosBridge callbackApi;
    public static WeakReference<Activity> mainGameActivity;
    private Method evalString;
    private Method runOnGLThread;
    private static Handler handler = new Handler(Looper.getMainLooper());

    public static BBounceCocosBridge getInstance() {
        if (callbackApi == null) {
            callbackApi = new BBounceCocosBridge();
        }
        return callbackApi;
    }

    public void setMainGameActivity(Activity activity) {
        mainGameActivity = new WeakReference<>(activity);

    }

    @Override
    public void XSSdkCallback(String action, String jsonData) {
        if (mainGameActivity != null && mainGameActivity.get() != null) {

            handler.post(() -> {

                check();

                try {
                    callback(action,jsonData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private void callback(String action, String jsonData) throws InvocationTargetException, IllegalAccessException {
        runOnGLThread.invoke(mainGameActivity.get(), (Runnable) () -> {
            try {
                evalString.invoke(null, String.format("window.AdCallback('%s','%s')", action, jsonData));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void check() {
        if (runOnGLThread==null){
            initRunOnGLThread();
        }
        if (evalString == null){
            initEvalString();
        }
    }

    private String commonPath = "org.cocos2dx.lib.";

    private void initEvalString() {
        try {
            Class clzBridge = Class.forName(commonPath+"Cocos2dxJavascriptJavaBridge", false, BBounceBusiness.context.getClassLoader());
            evalString = clzBridge.getDeclaredMethod("evalString", String.class);
            evalString.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initRunOnGLThread() {
        try {
            Class clzCocos2dAct = Class.forName(commonPath+"Cocos2dxActivity", false, BBounceBusiness.context.getClassLoader());
            runOnGLThread = clzCocos2dAct.getDeclaredMethod("runOnGLThread", Runnable.class);
            runOnGLThread.setAccessible(true);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
